package cn.bitkit.assist.doc;

import com.github.javaparser.ParseResult;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.javadoc.Javadoc;
import lombok.SneakyThrows;

import java.io.FileInputStream;
import java.util.concurrent.atomic.AtomicReference;

public class JavaDocHelper {

    private CompilationUnit compilationUnit;

    @SneakyThrows
    public static JavaDocHelper of(String file){
        JavaDocHelper helper = new JavaDocHelper();
        ParseResult<CompilationUnit> result = new JavaParser().parse(new FileInputStream(file));
        helper.compilationUnit = result.getResult().orElseThrow();
        return helper;
    }


    public String getClassDoc(){
        return getClassDoc(null);
    }

    public String getClassDoc(String tagName){
        AtomicReference<String> doc = new AtomicReference<>();
        compilationUnit.findAll(ClassOrInterfaceDeclaration.class).forEach(classOrInterfaceDeclaration -> {
            // 获取类注释
            classOrInterfaceDeclaration.getJavadoc().ifPresent(javadoc -> {
                doc.set(getJavaDoc(javadoc, tagName));
            });
        });
        return doc.get();
    }

    public String getFieldDoc(String fieldName){
        return getFieldDoc(fieldName,null);
    }

    public String getFieldDoc(String fieldName, String tagName){
        AtomicReference<String> doc = new AtomicReference<>();
        compilationUnit.findAll(FieldDeclaration.class).forEach(fieldDeclaration -> {
            fieldDeclaration.getVariables().getFirst()
                    .filter(e -> e.getName().toString().equals(fieldName))
                    .flatMap(e -> fieldDeclaration.getJavadoc())
                    .ifPresent(javadoc -> {
                        doc.set(getJavaDoc(javadoc, tagName));
            });
        });
        return doc.get();
    }

    private String getJavaDoc(Javadoc javadoc, String tagName){
        if(tagName == null){
            return javadoc.getDescription().toText();
        }else{
            // 获取所有标签
            return javadoc.getBlockTags().stream().filter(e -> e.getTagName().equals(tagName)).map(e -> e.getContent().toText()).findFirst().orElse(null);
        }
    }
}
